﻿using System;
using System.Text;
using KLS.PPDS.Utility.Extension;

namespace KLS.PPDS.Utility.Html
{
    public static class TextWrapExtension
    {
        public static string Wrap(this string value)
        {
            return value.Wrap(20);
        }
        public static string Wrap(this string value, int length)
        {
            return value.Wrap(length, " ");
        }
        public static string Wrap(this string value, int length, string seperator)
        {
            if (value.IsNullOrEmpty())
            {
                return value;
            }
            if (value.Length < length)
            {
                return value;
            }

            var words = value.Split(' ');
            var newValue = new StringBuilder();
            foreach (var word in words)
            {
                if (word.Length < length)
                {
                    newValue.AppendFormat("{0} ", word);
                }
                else
                {
                    for (int i = 0; i < word.Length; )
                    {                        
                        if ((i + length) > word.Length)
                        {
                            length = word.Length - i;
                        }
                        newValue.AppendFormat("{0}{1}", word.Substring(i, length), seperator);
                        i += length;
                    }
                    if (newValue.ToString().EndsWith(seperator, StringComparison.OrdinalIgnoreCase))
                    {
                        newValue.Length = newValue.Length - seperator.Length;
                    }
                }
            }

            return newValue.ToString();
        }
    }
}
